/*
 * @Author: mark
 * @Date: 2023-06-26 07:15:20
 * @LastEditors: mark
 * @LastEditTime: 2023-08-28 07:24:57
 * @FilePath: /自研/RuoYi_egg/ruoyi-egg/app/service/tool/redis.js
 * @Description:redis的基础操作
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */
const Service = require("egg").Service;
const time = 60 * 60 * 24 * 365; //默认缓存失效时间 365天
// 对应的标识与db的关系
const dbMap = {
  0: "client0",
  1: "client1",
};
class RedisService extends Service {
  constructor(ctx) {
    super(ctx);
    this.session = ctx.session;
    this.SysConfig = ctx.model.SysConfig;
    this.SysDictType = ctx.model.SysDictType;
    this.SysDictData = ctx.model.SysDictData;
    this.SysOperLog = ctx.model.SysOperLog;
    this.ResponseCode = ctx.response.ResponseCode;
    this.ServerResponse = ctx.response.ServerResponse;
    this.objUnderlineToHump = ctx.objUnderlineToHump;
    this.objHumpToUnderline = ctx.objHumpToUnderline;
    this.toInt = ctx.toInt;
  }

  //初始化设置redis
  async refreshRedis() {
    let config = [
      {
        cacheName: "sys_config",
        remark: "配置信息",
      },
      {
        cacheName: "sys_dict",
        remark: "数据字典",
      },
    ];

    //存入缓存
    await this.set(0, "config_name", config);
    //存入字典
    await this.setSysDict();
    //存入系统配置
    await this.setSysConfig();
  }

  /**
   * 存入字典数据
   */
  async setSysDict() {
    this.SysDictType.hasMany(this.SysDictData, {
      foreignKey: "dict_type",
      sourceKey: "dict_type",
    });
    let data = await this.SysDictType.findAll({
      include: [
        {
          model: this.SysDictData,
        },
      ],
    });
    data = data.map((item) => {
      item = item.dataValues;
      item.sys_dict_data = item.sys_dict_data.map((item2) => {
        return this.objUnderlineToHump(item2.dataValues);
      });
      item = this.objUnderlineToHump(item);
      return item;
    });
    let set = {};
    data.forEach((item) => {
      set[item.dictType] = item.sysDictData;
    });
    //存入缓存
    await this.set(0, "sys_dict", set);
  }

  /**
   * 存入系统配置缓存数据
   */
  async setSysConfig() {
    let data = await this.SysConfig.findAndCountAll(
      Object.assign({}, { raw: true })
    );
    let rows = data.rows;
    rows = rows.map((item) => {
      return this.objUnderlineToHump(item);
    });
    rows = rows.map((item) => {
      return {
        configKey: item.configKey,
        configValue: item.configValue,
      };
    });
    //存入缓存
    await this.set(0, "sys_config", rows);
  }

  // 设置
  async set(db, key, value, seconds) {
    // seconds 有效时长
    let { redis } = this.app;
    value = JSON.stringify(value);
    if (!seconds) {
      await redis.get(dbMap[db]).set(key, value);
    } else {
      // 设置有效时间
      await redis.get(dbMap[db]).set(key, value, "EX", seconds);
    }
  }

  // 获取
  async get(db, key) {
    let { redis } = this.app;
    let data = await redis.get(dbMap[db]).get(key);
    if (!data) return;
    data = JSON.parse(data);
    return data;
  }

  //获取所有key
  async getAllKeys(db = 0) {
    const { redis } = this.app;
    const keys = await redis.get(dbMap[db]).keys("*");
    return keys;
  }

  // 清空redis
  async flushall() {
    let { redis } = this.app;
    let setRedis = redis.get("client0");
    await setRedis.flushall();
    await this.refreshRedis();
    return;
  }
}
module.exports = RedisService;
